<?php
namespace app\blog\loglic;

use app\common\loglic\Model;

class Index extends Model
{
    //常用字段
    private $fields = 'detail_id,detail_name,detail_slug,detail_excerpt,detail_like,detail_hate,detail_view,detail_hit,detail_create_time,detail_letter,detail_slide,detail_cover';
    
    //初始查询参数
    private $args = [
        'where' => [],
        'cache' => false,
        'with'  => 'type,tag',
        'order' => [
            'detail_id' => 'desc',
        ],
    ];

    //修改器（写入数据库前）
    private function dataSet($data=[])
    {
        //固定链接
        $data['detail_slug'] = $this->autoSlug($data['detail_slug'],$data['detail_name']);
        //摘要截取
        if(!$data['detail_excerpt']){
            $data['detail_excerpt'] = xfSubstr(xfTrim($data['detail_content']), 0, 140, true);
        }
        //首字母
        if(!$data['detail_letter']){
            $data['detail_letter'] = substr($data['detail_slug'], 0, 1);
        }
        //扩展字段
        foreach($data['detail_extend'] as $key=>$value){
            if(!$value){
                unset($data['detail_extend'][$key]);
            }
        }
        //密码链接
        if(!$data['detail_extend']['passurl']){
            unset($data['detail_extend']['passurl']);
        }
        //栏目分类
        $dataTypeMap = [];
        foreach($data['type_id'] as $key=>$value){
            array_push($dataTypeMap,['type_mp_tid'=>$value]);
        }
        //标签聚合
        $dataTagMap = [];
        foreach($data['tag_id'] as $key=>$value){
            array_push($dataTagMap,['tag_mp_tid'=>$value]);
        }
        //模块定义
        $data['detail_mobile']   = 'blog';
        $data['detail_controll'] = 'index';
        return ['detail'=>$data,'type_map'=>$dataTypeMap,'tag_map'=>$dataTagMap];
    }

    //获取器（查询数据库后）
    private function dataGet($data=[])
    {
        if($data){
            $data['type_id']   = array_column($data['type'],'type_id');
            $data['type_name'] = array_column($data['type'],'type_name');
            $data['tag_id']   = array_column($data['tag'],'tag_id');
            $data['tag_name'] = array_column($data['tag'],'tag_name');
        }
        return $data;
    }

    /**
     * 添加一篇文章
     * @version 1.0.1 首次引入
     * @param array $data 必需;数组格式,支持的字段列表请参考手册
     * @param bool $autoSave 可选;当分类与标签不存在时是否自动新增;默认:false
     * @return int 返回自增ID或0
     */
    public function dataSave($data=[], $autoSave=false)
    {
        //数据初始化
        unset($data['detail_id']);
        //数据修改器
        $data = $this->dataSet($data, $autoSave);
        //表单验证规则
        $this->validateRule = [
            'detail_slug' => 'unique:detail,detail_slug^detail_module',
            'detail_referer' => 'unique:detail',
        ];
        $this->validateMsg = [
            'detail_slug.unique' => '唯一标识已存在',
            'detail_referer.unique' => '来源地址已存在',
        ];
        //表单验证未通过
        if(!$this->validateData($data['detail'])){
            return false;
        }
        //写入数据库
        return $this->modelSave('common/Detail',$data);
    }

    //修改一篇文章
    public function dataUpdate($data=[], $autoSave=false)
    {
        //数据修改器
        $data = $this->dataSet($data, $autoSave);
        //表单验证规则
        $this->validateRule = [
            'detail_id' => 'number',
            'detail_slug' => 'unique:detail,detail_slug^detail_module',
            'detail_referer' => 'unique:detail',
        ];
        $this->validateMsg = [
            'detail_id.number' => 'ID错误',
            'detail_slug.unique' => '唯一标识已存在',
            'detail_referer.unique' => '来源地址已存在',
        ];
        //表单验证未通过
        if(!$this->validateData($data['detail'])){
            return false;
        }
        //更新条件
        $where = [
            'detail_id' => $data['detail']['detail_id'],
        ];
        return $this->modelUpdate('common/Detail', $where, $data);
    }

    //按条件查询一篇文章（模型类）
    public function get($args=[])
    {
        return $this->modelGet('common/Detail', $args);
    }

    //按条件查询多条文章（模型类）
    public function all($args=[])
    {
        $args = array_merge($this->args,$args);

        array_push($args['where'],['detail_module','eq','blog']);

        return $this->ModelSelect('common/Detail', $args);
    }
    
    //按条件分页查询多条文章（模型类）
    public function allPage($args=[], $pageSize=10, $pageNumber=1, $isTotal=false, $pagePath='')
    {
        //合并参数
        $args = array_merge($this->args,$args);
        array_push($args['where'],['detail_module','eq','blog']);
        //查询数据
        $this->pageData = $this->modelSelectPage('common/Detail', $args, $pageSize, $pageNumber, xfTotal($isTotal), $pagePath);
        if($this->pageData->isEmpty()){
            $this->error = '数据为空';
            return NULL;
        }
        //合并分页
        $result = $this->pageData->toArray();
        $result['pages'] = $this->pageData->render();
        return $result;
        /*$list = $list->each(function($item, $key){
            $item->nickname = xfTypes($item['type']);
        });
        $list = $list->toArray();
        $list = $list->all();*/
    }

    //按ID查询一篇文章
    public function getId($id=0, $cache=false, $status=false, $with='type,tag')
    {
        $where = [
            ['detail_id','eq',$id],
        ];
        if($status){
            array_push($where,['detail_status','eq',$status]);
        }
        $result = $this->modelGet('common/Detail',[
            'cache' => $cache,
            'where' => $where,
            'with'  => $with,
        ]);
        return $this->dataGet($result);
    }

    //按标识查询一篇文章
    public function getSlug($id=0, $cache=false, $status=false, $with='type,tag')
    {
        $where = [
            ['detail_slug','eq',$id],
            ['detail_module','eq','blog'],
        ];
        if($status){
            array_push($where,['detail_status','eq',$status]);
        }
        $result = $this->modelGet('common/Detail',[
            'cache' => $cache,
            'where' => $where,
            'with'  => $with,
            //'fetchSql' => true,
        ]);
        return $this->dataGet($result);
    }

    /**
     * 按ID快速获取上一篇文章列表
     * @version 1.0.0 首次引入
     * @param int $id 必需;Id值;默认：空
     * @return array 查询结果
     */
    public function getPrevs($pkId=1, $limit=1)
    {   
        return $this->dbSelect('detail',[
            'limit' => $limit,
            'cache'  => config('cache.expire_items'),
            'field' => $this->fields,
            'order' => [
                'detail_id' => 'desc',
            ],
            'where' => [
                ['detail_module','eq','blog'],
                ['detail_status','eq','normal'],
                ['detail_id','lt',$pkId],
            ],
        ]);
    }

    /**
     * 按ID快速获取下一篇文章列表
     * @version 1.0.0 首次引入
     * @param int $id 必需;Id值;默认：空
     * @return array 查询结果
     */
    public function getNexts($pkId=1, $limit=1)
    {
        return $this->dbSelect('detail',[
            'limit' => $limit,
            'cache'  => config('cache.expire_items'),
            'field' => $this->fields,
            'order' => [
                'detail_id' => 'asc',
            ],
            'where' => [
                ['detail_module','eq','blog'],
                ['detail_status','eq','normal'],
                ['detail_id','gt',$pkId],
            ],
        ]);
    }

    //调用普通数据列表
    public function items($limit=10,$sort='detail_id',$order='desc',$field='*')
    {
        return $this->all([
            'field'  => $field,
            'limit'  => $limit,
            'cache'  => config('cache.expire_items'),
            'order'  => [
                $sort => $order,
            ],
            'where'  => [
                ['detail_status','eq','normal'],
                ['detail_module','eq','blog'],
            ],
        ]);
    }

    //按分类调用数据列表
    public function itemsType($typeId=0,$limit=10,$sort='detail_id',$order='desc',$field='*')
    {
        return $this->all([
            'field' => $field,
            'limit' => $limit,
            'cache' => config('cache.expire_items'),
            'order'  => [
                $sort => $order,
            ],
            'join'  => [
                ['type_map','type_map.type_mp_did = detail_id'],
            ],
            'where' => [
                ['detail_status','eq','normal'],
                ['detail_module','eq','blog'],
                ['type_map.type_mp_tid','eq',$typeId],
            ],
        ]);
    }

    //按标签调用数据列表
    public function itemsTag($tagId=0,$limit=10,$sort='detail_id',$order='desc',$field='*')
    {
        return $this->all([
            'field' => $field,
            'limit' => $limit,
            'cache' => config('cache.expire_items'),
            'order'  => [
                $sort => $order,
            ],
            'join'  => [
                ['tag_map','tag_map.tag_mp_did = detail_id'],
            ],
            'where' => [
                ['detail_status','eq','normal'],
                ['detail_module','eq','blog'],
                ['tag_map.tag_mp_tid','eq',$tagId],
            ],
        ]);
    }
}